<template>
  <div class="picking zy-content ">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.Entity') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.companyId" @on-change="changeCompany" clearable
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item, index) of tagList"
                        :value="item.id"
                        :key="item.id"
                        :label="item.name">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.Warehouse') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.backupConfigId" clearable
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item, index) of warehouseList"
                        :value="item.id"
                        :key="item.id"
                        :label="item.backupName">
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.ApprovalStatus') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.status"
                      clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="item in approvalList"
                        :value="item.id"
                        :label="item.name"
                        :key="item.id"
                />
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.Date') }}</p>
            <div class="ipt">
              <DatePicker clearable v-model="applyTimeList" type="datetimerange"
                          format="yyyy-MM-dd HH:mm:ss"
                          placement="bottom-end" :placeholder="`${$t('common.selectInfo')}`"
                          @on-change="handleRangeChange"/>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{ $t('common.ApprovalIsRequired') }}</p>
            <div class="ipt">
              <Select v-model="searchParams.ifNeedApproval"
                      clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option :value="1" :label="$t('是')"/>
                <Option :value="0" :label="$t('否')"/>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button class="search-btn"
                      v-has="'premiumSearch'"
                      type="primary"
                      @click="changeNum()">{{ $t('common.Query') }}</Button>
              <Button class="reset-btn"  v-has="'premiumSearch'"
                @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>

    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button   v-has="'premiumAdd'" @click="addRecipients('add')">{{ $t('common.NewScrap') }}</Button>
        <Button   v-has="'premiumExport'" @click="handleOutDel">{{ $t('common.batchExport') }}</Button>
          <Button @click="getTableColumns(columns)">
              {{ handleContextMenuStatus ? $t('显示操作栏') : $t('隐藏操作栏') }}
          </Button>
      </div>
      <div class="tableContent">
        <Table ellipsis ref="selection" @on-selection-change="onSelectChange"   class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
               :columns="columnsList" :data="dataArr">

          <template slot-scope="{ row }" slot="approvalResult">
            <span v-if="row.status === 1">{{ row.approvalResultStr }}</span>
            <span v-else>{{ row.statusStr }}</span>
          </template>
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn"
                  v-has="'premiumCheck'"
                  @click="addRecipients('detail', row)">
              <i class="iconfont zy-common-chakan"></i>
              <span>{{ $t('common.Check') }}</span>
             </span>
<template v-if="row.status === 1 && row.approvalResult === 1">
     <span class="operationBtn"
           v-has="'premiumWithdraw'"
           @click="deleteListInfo(row, 'callback')">
              <i class="iconfont zy-common-shibai1"></i>
              <span>{{ $t('common.Withdraw') }}</span>
            </span>
</template>

            <template  v-if="row.status === 1 && (row.approvalResult === 2 || row.approvalResult === 7)">
            <span class="operationBtn"
                  v-has="'premiumEdit'"
                  @click="addRecipients('edit', row)">
              <i class="iconfont zy-common-bianji"></i>
              <span>{{ $t('common.Edit') }}</span>
            </span>
            </template>

              <template  v-if="row.status === 1 && (row.approvalResult === 2 || row.approvalResult === 7)">
                <span class="operationBtn"
                      v-has="'premiumDelete'"
                      @click="deleteListInfo(row, 'delete')"><i
                    class="iconfont zy-common-shanchu"></i>
              <span>{{ $t('common.Delete') }}</span>
            </span>
              </template>

<!--            <span class="operationBtn"
                  v-if="Number(row.status) === -1"
                  @click="sumjbit(row)">
              <i class="iconfont zy-common-chenggong1"></i>
              <span>{{ $t('common.submit') }}</span>
            </span>-->
          </template>
        </Table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectList.length"/>
        <Page :total="total" :page-size="pageSize" :page-size-opts="pageSizeOption" :current="pageNum"
              @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
      </div>
    </div>


    <Modal :mask-closable="false" v-model="delShowstaus" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ tarStr }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="delShowstaus = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="deleteList">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import fileDownload from 'js-file-download'
import {getTableData} from "@/api/spare-parts/scrap-apply";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "picking",
  components: {},
    mixins:[toggleTableOperation],
  data() {
    return {
      delShowstaus: false,
      applyTimeList: [],
      formInfo: {},
      selectList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchParams: {},
      pageSizeOption: [10, 20, 30, 40],
      warehouseList: [],
      tagList: [{id: '', name: '全部'}],
      approvalList: [
        {id: 1, name: '已提交'},
        {id: 2, name: '撤回'},
        {id: 4, name: '审批通过'},
        {id: 5, name: '审批不通过'},
        {id: 7, name: '被退回'}
      ],
      columns: [
        {type: 'selection', width: 60, align: 'center'},
        {
          title: `${this.$t('spareParts.Approval')}`,
          key: 'ifNeedApprovalStr',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          //title: `${ this.$t('equipmentscrapped.ApplyTime') }`,
          title: `${this.$t('equipmentscrapped.ApplyTime')}`,
          key: 'applyTime',
          align: "center",
          minWidth: 130,
            resizable: true
        },
        {
          title: `${this.$t('spareParts.ApprovalStatus')}`,
          slot: 'approvalResult',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          // title: `${this.$t('spareParts.company')}`,
          title: `${this.$t('spareParts.company')}`,
          key: 'companyName',
          align: "center",
            resizable: true,tooltip: true,
          minWidth: 120
        },
        {
          // title: '仓库名称',
          title: `${this.$t('common.Warehouse')}`,
          key: 'warehouseName',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          //title: `${this.$t('common.ApplicationQuantit')}`,
          title: `${this.$t('common.ApplicationQuantit')}`,
          key: 'applyCount',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          //title: '申请人',
          title: `${this.$t('common.Appliedby')}`,
          key: 'applyBy',
          align: "center",
          minWidth: 120,
            resizable: true
        },
        {
          //操作
          title: `${this.$t('common.operation')}`,
          slot: "action",
          minWidth: 220,
          align: "center",
          fixed: 'right'
        }
      ],
      assetsList: [],
      dataArr: [],
      timerId: null,
      tarDelobj: {},
      tarStrinfo: "",
      tarStr: ''
    }
  },
  created() {
      this.getTableColumnsWidth(this.columns)
    this.getCompanyList()
    this.searchList()
  },
  methods: {
    reset(){
        this.searchParams = {};
        this.applyTimeList = []
        this.searchList()
    },
    sumjbit(row) {
      this.axios({
        method: 'get',
        url: '/dms/backup/scrapApply/submit',
        params: {
          applyId: row.id
        }
      }).then(res => {
        if (res.code == 200) {
          this.searchList()
        } else {
          this.$Message.error(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    //删除
    deleteListInfo(row, str) {
      this.tarDelobj = row
      this.tarStrinfo = str
      switch (str) {
        case 'delete':
          this.selectList = [this.tarDelobj]
          this.tarStr = '删除后不会继续生成报废申请任务，是否确认删除？'
          break;
        case 'callback':
          this.tarStr = '撤回后不会继续生成报废申请任务，是否确认撤回？'
          break;
      }
      this.delShowstaus = true
    },
    deleteList() {
      switch (this.tarStrinfo) {
        case 'delete':
          this.handleDel()
          break;
        case 'callback':
          this.backClick(this.tarDelobj)
          break;
      }
      this.delShowstaus = false
    },
    handleDel() {
      this.axios({
        method: 'post',
        url: '/dms/backup/scrapApply/deleteByIds',
        data: [this.tarDelobj.id]
      }).then(res => {
        if (res.code == 200) {
          this.searchList()
        } else {
          this.$Message.error(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    backClick({id}) {
      this.axios({
        method: 'get',
        url: '/dms/backup/scrapApply/rollBack',
        params: {
          applyId: id
        }
      }).then(res => {
        if (res.code == 200) {
          this.searchList()
        } else {
          this.$Message.error(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    addRecipients(str, row) {
      const query = {
        status: str,
        approvalFlowSort: '',
        statusStr: ''
      }
      if (str !== 'add') {
        if (row.id) {
          query.statusStr = row.status;
          // query.status = 'edit'
          query.id = row.id;
          query.approvalId = row.approvalId;
          query.approvalFlowSort = row.approvalFlowSort;
          this.$router.push({
            path: '/spareParts/operations/premium/addScrapApply',
            query
          })
        }
      } else {
        this.$router.push({
          path: '/spareParts/operations/premium/addScrapApply',
          query
        })
      }
    },
    changeCompany(val) {
      // let companyId;
      if (val) {
        // companyId = this.tagList.find(item => item.name == val).id
        this.getwarehouseList(val)
      } else {
        this.searchParams.warehouseId = ''
        this.warehouseList = []
      }
    },
    getwarehouseList(companyId) {
      this.warehouseList = []
      this.axios({
        method: 'post',
        url: '/dms/dmsBackupConfig/queryBackupsByCompany',
        data: {
          companyId
        }
      }).then(res => {
        if (res.data && res.data.length) {
          this.warehouseList = res.data
        }
      })
    },
    assetsChange() {
      if (this.timerId) {
        clearTimeout(this.timerId)
      }
      this.timerId = setTimeout(() => {
        this.axios({
          method: 'get',
          url: '/dms/dmsCheck/calculationAsset',
          params: {
            original: Number(this.formInfo.assetsOriginal),
            id: this.formInfo.id,
            assetId: this.formInfo.assetId
          }
        }).then(res => {
          this.formInfo.assets = res.data
        })
      }, 600)
    },
    onSelectChange(val) {
      this.selectList = val
    },
    //公司列表
    getCompanyList() {
      this.axios({
        method: 'get',
        url: '/basic/company/getCompanyListByUser',
        params: {}
      }).then(res => {
        
        if (res.code === 200) {
          let arr = res.data.map(item => {
            return {
              ...item,
              id: item.id.toString()
            }
          })
          this.tagList = [...this.tagList, ...arr]
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    handleRangeChange(val) {
      this.searchParams.startTime = val[0]
      this.searchParams.endTime = val[1]
    },
    //批量导出
    handleOutDel() {
      const delIds = this.selectList.map(val => val.id)
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      }
      if (delIds && delIds.length) {
        params['delIds'] = delIds
      }
      if (!params.ifNeedApproval) {
        delete params.ifNeedApproval
      }
      for (let key in params) {
        if (!params[key]) {
          delete params[key]
        }
      }
      const filName = '报废申请'
      this.axios({
        method: 'post',
        url: '/dms/backup/scrapApply/export',
        responseType: 'blob',
        data: params
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })
    },
    //刷新
    handleFresh() {
      this.searchList();
    },
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {
      let params = {
        pageNo: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      }
      // for (let key in params) {
      //   if (!params[key]) {
      //     delete params[key]
      //   }
      // }
      getTableData(params).then(res => {
        if (res.code === 200) {
          this.dataArr = res.data.list
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.picking {

  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;

    }
  }
}
</style>

